import { useState } from 'react'
import { Button, message, Modal, Flex, Tag, Input, Row, Col, Space } from 'antd'
import { ModalForm, ProFormDigit, ProFormItem, ProFormText, ProFormUploadButton } from '@ant-design/pro-components'
import { PlusOutlined, ExclamationCircleFilled, EyeOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { deleteKey, queryDetailByKey, renameKey, setKeyTTL } from '@/api/sharing/redis'
import CodeEditor from '@/components/codemirror/CodeEditor'
import { useEffect, useRef } from 'react'
import HashValue from './value/HashValue'
import StringValue from './value/StringValue'
import ListValue from './value/ListValue'
import SetValue from './value/SetValue'
import ZSetValue from './value/ZSetValue'

const keyColorMap = { hash: '#70b603', list: '#3aa8ff', set: '#8400ff', zset: '#ff0000', string: '#f59a23' }

//i18n
const RedisRightPanel = ({ currentSource, onTransferLeftPanel }) => {
  const [isFetching, setIsFetching] = useState(false)
  const [fullData, setFullData] = useState({})
  const confirm = Modal.confirm
  const valueRef = useRef()


  useEffect(() => {
    if (currentSource && !fullData?.result) {
      getQueryDetail()
    }
  }, [currentSource])

  const getQueryDetail = () => {
    setIsFetching(true)
    queryDetailByKey({
      id: currentSource.connectInfo.id,
      key: currentSource.key,
      type: currentSource.tag.toLocaleUpperCase(),
      database: currentSource.database
    }).then((res) => {
      setFullData(res.result || {})
    }).finally(() => {
      setIsFetching(false)
    })
  }


  // 重命名key
  const handleRenameKey = (values) => {
    return renameKey(values).then((res) => {
      if (res.code == 200) {
        message.success('重命名成功')
        onTransferLeftPanel('renameKey', values)
        return true
      }
    })
  }
  // 删除key
  const handleDeleteKey = () => {
    confirm({
      title: '确认删除该key数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        const params = {
          id: currentSource?.connectInfo.id,
          database: currentSource?.database,
          key: currentSource?.key,
          type: currentSource?.tag.toLocaleUpperCase(),
        }
        return deleteKey(params).then((res) => {
          if (res.code == 200) {
            onTransferLeftPanel('deleteKey', params)
            message.success('删除成功')
          }
        })
      },
      onCancel() { },
    })
  }

  const handleSetKeyTTL = (values) => {
    return setKeyTTL(values).then((res) => {
      if (res.code == 200) {
        message.success('设置TTL成功')
        setFullData({ ...fullData, ttl: values.ttl })
        return true
      }
    })
  }

  const handleSave = () => {
    valueRef.current.save()
  }

  return (
    <>
      <Row style={{ flex: 0 }}>
        <Col span={16}>
          <div><Input value={currentSource?.key} readOnly={true} /></div>
          <div style={{ marginTop: 10, lineHeight: '32px' }}>
            <Space>
              <span>key类型：<Tag style={{ width: 42, lineHeight: '18px', padding: 0, textAlign: 'center' }} color={keyColorMap[currentSource?.tag || 'string']}>{currentSource?.tag || 'string'}</Tag></span>
              {currentSource?.tag === 'hash' && <span>field数量：<Tag>{fullData?.fieldNum || 0}</Tag></span>}
              <span>value：<Tag>{fullData?.value || 0}</Tag></span>
              <span>TTL：<Tag>{fullData?.ttl || -1}</Tag></span>
            </Space>
          </div>
        </Col>
        <Col span={8} className='right-panel-btn-wrapper'>
          {/* <RenameKeyBtn initialValues={{
            id: currentSource?.connectInfo?.id,
            database: currentSource?.database,
            oldKey: currentSource?.key,
            newKey: currentSource?.key
          }} onFinish={handleRenameKey} /> */}

          <SetKeyTTLBtn initialValues={{
            id: currentSource?.connectInfo?.id,
            database: currentSource?.database,
            key: currentSource?.key,
            ttl: fullData?.ttl == -1 ? '' : fullData?.ttl
          }} onFinish={handleSetKeyTTL} />
          <Button disabled={!currentSource} danger onClick={handleDeleteKey}>
            删除key
          </Button>
          <div style={{ marginTop: 10 }}>
            <Button disabled={!currentSource} type="primary" onClick={handleSave}>
              保存value
            </Button>
            <Button disabled={!currentSource} type="primary" onClick={getQueryDetail}>
              刷新value
            </Button>
          </div>
        </Col>
      </Row>
      {(currentSource?.tag === 'string' || !currentSource) && <StringValue ref={valueRef} currentSource={currentSource} refetch={getQueryDetail} fullData={fullData} isFetching={isFetching} />}
      {currentSource?.tag === 'hash' && <HashValue ref={valueRef} onTransferLeftPanel={onTransferLeftPanel} currentSource={currentSource} refetch={getQueryDetail} fullData={fullData} isFetching={isFetching} />}
      {currentSource?.tag === 'list' && <ListValue ref={valueRef} onTransferLeftPanel={onTransferLeftPanel} currentSource={currentSource} refetch={getQueryDetail} fullData={fullData} isFetching={isFetching} />}
      {currentSource?.tag === 'set' && <SetValue ref={valueRef} onTransferLeftPanel={onTransferLeftPanel} currentSource={currentSource} refetch={getQueryDetail} fullData={fullData} isFetching={isFetching} />}
      {currentSource?.tag === 'zset' && <ZSetValue ref={valueRef} onTransferLeftPanel={onTransferLeftPanel} currentSource={currentSource} refetch={getQueryDetail} fullData={fullData} isFetching={isFetching} />}
    </>
  )
}

const RenameKeyBtn = (props) => {
  return (
    <ModalForm
      width={'400px'}
      trigger={<Button type="primary">重命名key </Button>}
      title="重命名key"
      modalProps={{ destroyOnClose: true }}
      onFinish={props.onFinish}
      grid={true}
      {...props}
    >
      <ProFormItem name="id" hidden />
      <ProFormItem name="database" hidden />
      <ProFormItem name="oldKey" hidden />
      <ProFormText name="newKey" placeholder="请输入新key" rules={[{ required: true, message: '请输入新key' }]} />
    </ModalForm>
  )
}

const SetKeyTTLBtn = (props) => {
  return (
    <ModalForm
      width={'400px'}
      trigger={<Button type="primary" disabled={!props.initialValues?.id}>设置TTL</Button>}
      title="设置TTL"
      modalProps={{ destroyOnClose: true }}
      onFinish={props.onFinish}
      grid={true}
      {...props}
    >
      <ProFormItem name="id" hidden />
      <ProFormItem name="database" hidden />
      <ProFormItem name="key" hidden />
      <ProFormDigit name="ttl" fieldProps={{ min: 0, precision: 0 }} placeholder="请输入ttl" rules={[{ required: true, message: '请输入ttl' }]} />
    </ModalForm>
  )
}

export default RedisRightPanel
